﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace WebChatClient.Controllers
{
    public class ChatController : Controller
    {

        HttpClient httpclient = new HttpClient();
        List<Chatter> ListChatter = new List<Chatter>();
        List<Chatter> FriendList;
        public ChatController()
        {
            httpclient.BaseAddress = new System.Uri("http://localhost:63046/");
            httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            FriendList = new List<Chatter>();
        }
        //
        [HttpGet]
        public Object getFriends()
        {


            List<FriendConnection> ListFriendConnection = new List<FriendConnection>();

            HttpResponseMessage response = httpclient.GetAsync("api/ChatterAPI").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var friends = response.Content.ReadAsAsync<IEnumerable<Chatter>>().Result;
                foreach (var p in friends)
                {
                    FriendList.Add(p);
                }

            }

            HttpResponseMessage response2 = httpclient.GetAsync("api/FriendConnectionAPI").Result;  // Blocking call!
            if (response2.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var friendships = response2.Content.ReadAsAsync<IEnumerable<FriendConnection>>().Result;
                foreach (var p in friendships)
                {
                    ListFriendConnection.Add(p);
                }

            }

            string myname = User.Identity.Name;
            List<Chatter> Myfriendlist = new List<Chatter>();

            for (int i = 0; i < ListFriendConnection.Count; i++)
            {
                if (ListFriendConnection[i].ChatterName == User.Identity.Name)
                {
                    for (int j = 0; j < FriendList.Count; j++)
                    {
                        if (FriendList[j].Nick == ListFriendConnection[i].FriendName)
                        {
                            Myfriendlist.Add(FriendList[j]);
                        }
                    }

                }
            }

            Chatter Me = new Chatter();
            Me.Nick = User.Identity.Name;
            Myfriendlist.Add(Me);

            JavaScriptSerializer sr = new JavaScriptSerializer();
            var list = sr.Serialize(Myfriendlist);
           
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public Object getMessages()
        {
            string url_id = "http://localhost:63046/api/ChatterMessageAPI";

            System.Uri myUri = new System.Uri(url_id);

            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url_id);

            // ---- Set GET method -----
            myHttpWebRequest.Method = "GET";

            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

            var stream = myHttpWebResponse.GetResponseStream();
            var reader = new StreamReader(stream);
            string html = reader.ReadToEnd();
            return Json(html, JsonRequestBehavior.AllowGet);
        }

        //update message
        [HttpPost]
        public bool updateMessage(string newmessage)
        {
            if (ModelState.IsValid)
            {
                ChatterMessage newmes = new ChatterMessage();
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                newmes = (ChatterMessage)serializer.Deserialize(newmessage, newmes.GetType());
                System.Uri messageUri = new System.Uri("http://localhost:63046/api/ChatterMessageAPI/" + newmes.ID);
                newmes.IsRead = 0;
                HttpResponseMessage respone = httpclient.PutAsJsonAsync(messageUri.PathAndQuery, newmes).Result;

                if (respone.IsSuccessStatusCode)
                {
                    return true;
                }
            }
            return false;
        }
        //Create Message
        [HttpPost]
        public bool createMessage(string newmessage, string To)
        {

            ChatterMessage newmes = new ChatterMessage();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            // newmes = (Client_Chat.Models.Message)serializer.Deserialize(newmessage, newmes.GetType());
            System.Uri messageUri = new System.Uri("http://localhost:63046/api/ChatterMessageAPI");
            newmes.IsRead = 1;
            newmes.Text = newmessage;
            newmes.ReceiverName = To;
            newmes.SenderName = User.Identity.Name;
            HttpResponseMessage respone = httpclient.PostAsJsonAsync(messageUri.PathAndQuery, newmes).Result;
            if (respone.IsSuccessStatusCode)
            {
                return true;
            }

            return false;
        }

        //
        // GET: /Chat/

        public ActionResult Index()
        {
            Chatter tempchatter = GetCurrentChatterModel();
            return View(tempchatter);
        }

        private Chatter GetCurrentChatterModel()
        {
            Chatter tempchatter = new Chatter();
            string CurrentUserNick = User.Identity.Name;


            // Get the chatter list from the server
            HttpResponseMessage response = httpclient.GetAsync("api/ChatterAPI").Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var products = response.Content.ReadAsAsync<IEnumerable<Chatter>>().Result;
                foreach (var p in products)
                {
                    ListChatter.Add(p);
                }
            }

            //Compare the name to get right model

            for (int i = 0; i < ListChatter.Count; i++)
            {
                if (ListChatter[i].Nick == CurrentUserNick)
                    tempchatter = ListChatter[i];
            }
            return tempchatter;
        }

        [HttpPost]
        public void AddFriendConnection(string FriendName)
        {
            FriendConnection fc = new FriendConnection();
            fc.ChatterName = User.Identity.Name;
            fc.FriendName = FriendName;
            HttpResponseMessage response2 = httpclient.PostAsJsonAsync("/api/FriendConnectionAPI", fc).Result;
            if (response2.IsSuccessStatusCode)
            {

            }
        }

        [HttpPost]
        public void DeleteFriendConnection(string FriendName)
        {
            FriendConnection temp = new FriendConnection();
            List<FriendConnection> ListFriendConnection = new List<FriendConnection>();
            HttpResponseMessage response2 = httpclient.GetAsync("api/FriendConnectionAPI").Result;  // Blocking call!
            if (response2.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var friendships = response2.Content.ReadAsAsync<IEnumerable<FriendConnection>>().Result;
                foreach (var p in friendships)
                {
                    ListFriendConnection.Add(p);
                }

            }

            for (int i = 0; i < ListFriendConnection.Count; i++)
            {
                if (ListFriendConnection[i].FriendName == FriendName && ListFriendConnection[i].ChatterName == User.Identity.Name)
                    temp = ListFriendConnection[i];
            }

            HttpResponseMessage respone3 = httpclient.DeleteAsync("api/FriendConnectionAPI/" + temp.ID).Result;
            if (respone3.IsSuccessStatusCode)
            {

            }
        }
    }
}
